<script setup>
import request from "@/utils/request";

import { getToken } from "@/utils/auth";

import useSettingsStore from "@/store/modules/settings";

const props = defineProps({
  // 是否开启
  isShow: {
    type: Boolean,
    default: false,
  },
  // 导入接口
  importUrl: {
    type: String,
    default: "",
  },
  // 模板接口
  templateUrl: {
    type: String,
    default: "",
  },
  // 数量限制
  limit: {
    type: Number,
    default: 5,
  },
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 5,
  },
  // 文件类型, 例如['png', 'jpg', 'jpeg']
  fileType: {
    type: Array,
    default: () => ["doc", "xls", "ppt", "txt", "pdf", "xlsx"],
  },
  // 是否显示提示
  isShowTip: {
    type: Boolean,
    default: true,
  },
  //1导入 2报表导入
  num: {
    type: String,
    default: "",
  },
  /**
   * 是否需要下载模版
   */
  isNeedUpload: {
    type: Boolean,
    default: true,
  },
});

const { proxy } = getCurrentInstance();

const emit = defineEmits(["update:isShow", "close"]);

const isShoaw = ref(false);

// 文件路径
const file = ref("");

//使用计算属性
const uploadFileUrl = computed(() => {
  return import.meta.env.VITE_APP_BASE_API + props.importUrl;
});

// const headers = ref({ Authorization: "Bearer " + getToken() });
const headers = ref({ Authorization: getToken() });

/**
 * 表格枚举
 */
const columns = ref([
  { label: "导入总条数", prop: "total" },
  { label: "成功条数", prop: "requestId" },
  { label: "失败条数", prop: "errorTotal" },
]);
const fileList = ref([]);

const importListShow = ref(false);

//使用inject接收爷组件发送的数据,假如没有就用后面的路径
const isNeederrList = inject("isNeederrList"); //是否需要错误列表
const isNeedUpload = inject("isNeedUpload"); //是否需要下载模版

// 列表枚举
const column = ref([
  { label: "导入总条数", prop: "total" },
  { label: "成功条数", prop: "successTotal" },
  { label: "失败条数", prop: "errorTotal" },
  { label: "错误信息", prop: "contactPerson" },
]);

const tableData = ref([]);
// 关闭
const closeSub = () => {
  file.value = "";
  fileList.value = [];
  emit("update:isShow", false);
  // emit("close");
};

// 上传前校检格式和大小
function handleBeforeUpload(file) {
  // 校检文件类型
  if (props.fileType.length) {
    const fileName = file.name.split(".");
    const fileExt = fileName[fileName.length - 1];
    const isTypeOk = props.fileType.indexOf(fileExt) >= 0;
    if (!isTypeOk) {
      proxy.$modal.msgError(
        `文件格式不正确, 请上传${props.fileType.join("/")}格式文件!`
      );
      return false;
    }
  }
  // 校检文件大小
  if (props.fileSize) {
    const isLt = file.size / 1024 / 1024 < props.fileSize;
    if (!isLt) {
      proxy.$modal.msgError(`导入文件大小不能超过 ${props.fileSize} MB!`);
      return false;
    }
  }
  proxy.$modal.loading("正在导入文件，请稍候...");
  return true;
}

const fillfileList = ref([]);

const data = ref({});
// 成功
const success = (res) => {
  proxy.$modal.closeLoading();
  console.log(res.code, "ees");
  try {
    if (res.code != 200) {
      proxy.errorMsg(res.msg + " ==>请重新整理数据再次导入！");
      fileList.value = [];
      return;
    }

    data.value = res.data;
    if (res.code == 200) {
      fillfileList.value.push(res.data || {});
      emit("close");
      importListShow.value = true;
      proxy.successMsg("导入成功！");
    }
    // if (res.data.errorList.length > 0) {
    //   fillfileList.value = res.data.errorList;
    // } else {
    //   fillfileList.value = res.data.successList;
    // }
  } catch (error) {
  } finally {
    proxy.$modal.closeLoading();
  }
};

// 失败
const error = (err) => {
  proxy.$modal.closeLoading();
  proxy.errorMsg("导入失败！==>" + err);
};
</script>

<template>
  <p-dialog
    :isBtn="false"
    :v-model="props.isShow"
    :title="`${useSettingsStore().title}导入`"
    @close="closeSub"
    width="35rem"
  >
    <div class="item">
      <el-form label-width="120px">
        <el-form-item label="下载模板" v-if="props.isNeedUpload">
          <el-link
            type="primary"
            @click="proxy.download(templateUrl, {}, '.xlsx')"
            >{{
              props.num == "1"
                ? `下载${useSettingsStore().title}模板`
                : `下载${useSettingsStore().title}报表导入模板`
            }}</el-link
          >
        </el-form-item>
        <el-form-item label="上传导入文档">
          <el-upload
            :headers="headers"
            :action="uploadFileUrl"
            :file-list="fileList"
            @change="change"
            :limit="1"
            :before-upload="handleBeforeUpload"
            :on-success="success"
            :on-error="error"
          >
            <el-button type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>

        <!-- <el-form-item label="导入错误列表">
          <el-button type="primary" @click="importListShow = true"
            >查看导入列表</el-button
          >
        </el-form-item> -->
      </el-form>
      <div class="item-bottom">
        <div>注意事项:</div>
        <p>1、只能导入模版文件;</p>
        <p>2、模版内带*字段必填,否则导入失败;</p>
        <p>3、系统内无对应数据时,导入后对应显示为空;</p>
        <p>4、模版表头不支持编辑;</p>
      </div>
    </div>

    <!-- <p-importList
      :isShow="importListShow"
      @cancel="importListShow = false"
      :column="column"
      :list="fillfileList"
      title="导入列表"
      :data="data"
    /> -->
  </p-dialog>
</template>
<style scoped lang="scss">
.item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.item-bottom {
  p {
    color: red;
  }

  div {
    font-size: 16px;
    font-weight: 700;
  }
}
</style>